package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Resource
    private OrderMapper orderMapper;
    /**
     * 处理超时未支付订单
     * 每分钟0秒执行一次
     */
    @Scheduled(cron = "0 * * * * ?" )
    public void timeoutOrder(){
        //通过定时任务,每分钟的0秒找出符合筛选规则的订单
        //筛选的订单,状态为1,时间状态为小于当前时间-15分钟的时间的订单
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取15分钟前的时间
        LocalDateTime minusMinutes = now.minusMinutes(15);
        List<Long> ordersId = orderMapper.getOrderByStatusAndTime(Orders.PENDING_PAYMENT, minusMinutes);
        if(ordersId.size() > 0){
            Orders orders = new Orders();
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("超时未支付订单,自动取消");
            orders.setCancelTime(now);

            orderMapper.updateOrder(orders,ordersId);
        }
    }

    /**
     * 处理派送中订单
     */
    @Scheduled(cron = "* 30 * * * ?")
    public void unFinish(){
        LocalDateTime now = LocalDateTime.now();
        //获取15分钟前的时间
        LocalDateTime minusMinutes = now.minusMinutes(60);
        List<Long> ordersId = orderMapper.getOrderByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, minusMinutes);
        if(ordersId.size() > 0){
            Orders orders = new Orders();
            orders.setStatus(Orders.COMPLETED);
            orderMapper.updateOrder(orders,ordersId);
        }
    }
}
